import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/app_colors.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_page/cartoon_business/audio_player_bottomsheet.dart';
import 'package:xvideos/hj_page/cartoon_business/widget/acg_source_manager.dart';
import 'package:xvideos/hj_utils/date_time_util.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/widget/net_image_widget.dart';

class AudioPlayerValue {
  Duration? position;
  Duration? duration;
  bool? isPlaying;
  bool isLooping;
  double volume;
  bool isCompleted;
  bool isInitialized;
  int? onPlayIndex;

  AudioPlayerValue(
      {this.position,
      this.duration,
      this.isPlaying,
      this.volume = 1,
      this.isLooping = true,
      this.isCompleted = false,
      this.isInitialized = false,
      this.onPlayIndex});
  static AudioPlayerValue copyWith(AudioPlayerValue value) {
    return AudioPlayerValue(
        duration: value.duration,
        position: value.position,
        isPlaying: value.isPlaying,
        isCompleted: value.isCompleted,
        volume: value.volume,
        isLooping: value.isLooping,
        isInitialized: value.isInitialized,
        onPlayIndex: value.onPlayIndex);
  }
}

// 播放页面
class AudioPlayerContent extends StatefulWidget {
  final int index;
  final AudioPlayerManager manager;
  final ACGSourceManager sourceManager;
  const AudioPlayerContent(this.sourceManager, {super.key, required this.manager, this.index = 0});

  @override
  State<AudioPlayerContent> createState() => _AudioPlayerContentState();
}

class _AudioPlayerContentState extends State<AudioPlayerContent> with TickerProviderStateMixin {
  AudioPlayerManager get manager => widget.manager;
  AudioPlayMod playMod = AudioPlayMod.loopList;

  @override
  void initState() {
    super.initState();
    manager.initPlayer();
    // 自动播放第一
    manager.play(widget.sourceManager.allEpisodes[widget.index].getRealAudioUrl);
  }

  @override
  void didUpdateWidget(covariant AudioPlayerContent oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void dispose() {
    manager.dispose();
    manager.audioValue.removeListener(() {});
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: manager.audioValue,
      builder: (ctx, value, child) {
        double max = (value.duration?.inSeconds ?? 1).toDouble();
        if (max == 0) max = 1;
        final position = (value.position?.inSeconds ?? 0).toDouble();
        return Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            12.sizeBoxH,
            NetworkImageLoader(
              imageUrl: widget.sourceManager.mediaInfo?.coverH ?? '',
              width: 111,
              height: 148,
            ),
            18.sizeBoxH,
            Row(
              children: [
                Text(
                  '正在播放：第${(value.onPlayIndex ?? 0) + 1}集',
                  style: TextStyle(color: Colors.white.withOpacity(.9), fontSize: 16.sp, fontWeight: FontWeight.w500),
                ),
              ],
            ),
            18.sizeBoxH,
            Row(
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    InkWell(
                      onTap: () => manager.seekTenMinsWithDirection(-1),
                      child: Image.asset('noval_time_back.png'.acgImgPath, width: 24),
                    ),
                    8.sizeBoxH,
                    SizedBox(
                      width: 35,
                      height: 19,
                      child: Text(
                        buildMMSS(value.position?.inSeconds ?? 0),
                        style: TextStyle(color: Colors.white.withOpacity(.9), fontSize: 12, fontWeight: FontWeight.w500),
                      ),
                    ),
                  ],
                ),
                10.sizeBoxW,
                Expanded(
                  child: AudioSlider(
                    value: position / max,
                    onChange: (value) {
                      manager.seek((max * value).toInt());
                    }, //进度
                  ),
                ),
                10.sizeBoxW,
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    InkWell(
                      onTap: () => manager.seekTenMinsWithDirection(1),
                      child: Image.asset('noval_time_forword.png'.acgImgPath, width: 24),
                    ),
                    8.sizeBoxH,
                    SizedBox(
                      width: 35,
                      height: 19,
                      child: value.duration == null
                          ? CupertinoActivityIndicator(color: Colors.white)
                          : Text(
                              buildMMSS(value.duration!.inSeconds),
                              style: TextStyle(
                                color: Colors.white.withOpacity(.9),
                                fontSize: 12,
                                fontWeight: FontWeight.w500,
                                height: 1,
                              ),
                            ),
                    )
                  ],
                )
              ],
            ),
            14.sizeBoxH,
            Row(
              children: [
                InkWell(
                    child: Column(
                      children: [
                        Image.asset(
                          playMod == AudioPlayMod.loop ? 'single_cycle.png'.acgImgPath : 'list_cycle.png'.acgImgPath,
                          width: 24,
                        ),
                        2.sizeBoxH,
                        Text(
                          playMod == AudioPlayMod.loop ? '单曲循环' : '多集循环',
                          style: TextStyle(color: Colors.white.withOpacity(.9), fontSize: 12, fontWeight: FontWeight.w400),
                        )
                      ],
                    ),
                    onTap: () {
                      if (playMod == AudioPlayMod.loop) {
                        manager.setPlayMod(AudioPlayMod.loopList);
                        playMod = AudioPlayMod.loopList;
                      } else {
                        manager.setPlayMod(AudioPlayMod.loop);
                        playMod = AudioPlayMod.loop;
                      }
                    }),
                Spacer(),
                Row(
                  children: [
                    InkWell(
                      child: Image.asset('forward.png'.acgImgPath, width: 24),
                      onTap: () => manager.playForward(),
                    ),
                    40.sizeBoxW,
                    InkWell(
                      child: Image.asset(
                        (value.isPlaying ?? false) ? 'pause.png'.acgImgPath : 'play.png'.acgImgPath,
                        width: 36,
                      ),
                      onTap: () => (value.isPlaying ?? false) ? manager.pause() : manager.resume(),
                    ),
                    40.sizeBoxW,
                    InkWell(
                      child: Image.asset('next.png'.acgImgPath, width: 24),
                      onTap: () => manager.playNext(),
                    ),
                  ],
                ),
                Spacer(),
                InkWell(
                  child: Column(
                    children: [
                      Image.asset('play_list.png'.acgImgPath, width: 24),
                      2.sizeBoxH,
                      Text(
                        '播放列表',
                        style: TextStyle(
                          color: Colors.white.withOpacity(.9),
                          fontSize: 12,
                          fontWeight: FontWeight.w400,
                        ),
                      )
                    ],
                  ),
                  onTap: () {
                    Get.bottomSheet(AudioPlayerBottomSheet(
                      manager.sourceManger?.mediaInfo?.title ?? '',
                      currentPlayIndex: widget.sourceManager.index,
                      allAudiobooks: manager.sourceManger?.allEpisodes ?? [],
                      indexHandler: (index) {
                        manager.playWithIndex(index);
                      },
                    ));
                  },
                ),
              ],
            ),
            18.sizeBoxH,
          ],
        );
      },
    );
  }
}

//播放器进度条滑杆
class AudioSlider extends StatefulWidget {
  final double? value;

  final Function(double value) onChange;

  AudioSlider({super.key, required this.value, required this.onChange});

  @override
  State<AudioSlider> createState() => _AudioSliderState();
}

class _AudioSliderState extends State<AudioSlider> {
  final globalKey = GlobalKey();
  double _width = 0;

  bool _isStart = false;

  double _dx = 0.0;

  double _getThumbDx() {
    if (!_isStart) _dx = (_width - 16) * (widget.value ?? 1);
    return _dx;
  }

  double _getSliderValue() {
    if (!_isStart) return widget.value ?? 1;
    return _dx / (_width - 16);
  }

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      final redb = globalKey.currentContext?.findRenderObject() as RenderBox?;
      _width = redb?.size.width ?? 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      key: globalKey,
      height: 24,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onHorizontalDragStart: (start) {
          _isStart = true;
        },
        onHorizontalDragUpdate: (update) {
          _dx += update.delta.dx;
          if (_dx < 0) _dx = 0;
          if (_dx > _width - 16) _dx = _width - 16;
          print('onHorizontalDragUpdate ${update.delta.dx}       $_dx');

          setState(() {});
        },
        onHorizontalDragEnd: (end) {
          // final dx_ = end.
          _isStart = false;
          widget.onChange(_dx / (_width - 16));
        },
        onTapDown: (tap) {
          print(tap);
          _dx = tap.localPosition.dx;
          widget.onChange(_dx / (_width - 16));
        },
        child: Stack(
          alignment: Alignment.centerLeft,
          children: [
            Container(
              width: double.infinity,
              margin: EdgeInsets.symmetric(horizontal: 8),
              child: CustomPaint(painter: SliderPainter(_getSliderValue())),
            ),
            Positioned(
              left: _getThumbDx(),
              child: Image.asset(
                'slider_thumb.png'.acgImgPath,
                width: 16,
                height: 16,
                alignment: Alignment.center,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class SliderPainter extends CustomPainter {
  late Paint _paint = Paint();

  double end = 0;
  SliderPainter(this.end);
  @override
  void paint(Canvas canvas, Size size) {
    _paint.color = Color(0xff3D3D3D);
    _paint.strokeWidth = 2;
    _paint.strokeCap = StrokeCap.round;
    canvas.drawLine(Offset(0, 0), Offset(size.width, 0), _paint);
    _paint.color = AppColors.actionRed;
    canvas.drawLine(Offset(0, 0), Offset(size.width * end, 0), _paint);
  }

  @override
  bool shouldRepaint(SliderPainter oldDelegate) => end != oldDelegate.end;

  @override
  bool shouldRebuildSemantics(SliderPainter oldDelegate) => end != oldDelegate.end;
}
